import { UploadOutlined } from '@ant-design/icons'
import { FC, useContext, useEffect, useState } from 'react'
import { Button, Form, Input, Upload, message, Image } from 'antd'
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface'
import Bread from '@/component/bread/bread'
import { AppContext } from '@/App'
import { useNavigate } from 'react-router-dom'
import { TStore } from '@type'
import axios from '@/http'
import { VideoContext } from '../video'
const { TextArea } = Input
const AddVideo: FC<{ origin?: string }> = ({ origin = 'add' }) => {
  const [loading, setloading] = useState(false)
  const videoInfo = useContext(VideoContext)
  useEffect(() => {
    form.setFieldsValue(videoInfo)
  }, [videoInfo])
  const fillVideoInfo = () => {
    form.resetFields()
  }
  const nav = useNavigate()
  const onFinish = (values: any) => {
    setloading(true)
    const uploadValues = { ...values }
    let formData = new FormData()
    for (const data in uploadValues) {
      formData.append(data, uploadValues[data])
    }
    formData.append('mp4file', fileList[0] as RcFile)
    formData.append('mp4file', videoFileList[0] as RcFile)
    origin !== 'add' && formData.append('id', videoInfo.id + '')
    const url = origin === 'add' ? '/upload/upMp4' : '/upload/update'
    axios
      .post(url, formData)
      .then(res => {
        res.data.error === -1 && nav('/index/video')
      })
      .finally(() => {
        setloading(false)
      })
  }
  const [form] = Form.useForm()
  const bread = ['视频', '视频添加']
  const [fileList, setFileList] = useState<UploadFile<RcFile>[]>([])
  const [videoFileList, setVideoFileList] = useState<UploadFile[]>([])
  const beforeUpload = (file: RcFile) => {
    if (fileList.length !== 0) {
      return false
    }
    uploadImgVaild(file) && preImg(file) && setFileList([...fileList, file])
    return false
  }
  const beforeVideoUpload = (file: RcFile) => {
    if (videoFileList.length !== 0) {
      return false
    }
    uploadVideoVaild(file) && setVideoFileList([...videoFileList, file])

    return false
  }
  const uploadImgVaild = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) {
      message.error('你仅能上传jpg和png的图片!')
      return false
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('图片大小必须小于2MB!')
      return false
    }
    return true
  }
  const uploadVideoVaild = (file: RcFile) => {
    const [type] = file.type.split('/')
    // const isJpgOrPng = file.type === 'audio/mpeg'
    if (type !== 'audio') {
      message.error('你仅能上传媒体文件!')
      return false
    }
    const isLtSize = file.size / 1024 / 1024 < 100
    if (!isLtSize) {
      message.error('文件大小必须小于100MB!')
      return false
    }
    return true
  }
  const props: UploadProps = {
    maxCount: 1,
    onRemove: file => {
      const index = fileList.indexOf(file)
      const newFileList = fileList.slice()
      newFileList.splice(index, 1)
      setFileList(newFileList)
    },
    beforeUpload: file => beforeUpload(file)
  }
  const videoProps: UploadProps = {
    maxCount: 1,
    onRemove: file => {
      const index = videoFileList.indexOf(file)
      const newVideoFileList = videoFileList.slice()
      newVideoFileList.splice(index, 1)
      setVideoFileList(newVideoFileList)
    },
    beforeUpload: file => beforeVideoUpload(file)
  }
  const [picture, setPicture] = useState<string>(videoInfo.poster || '')
  const normFile = (e: any) => {
    console.log('Upload event:', e)
    if (Array.isArray(e)) {
      return e
    }
    return e?.fileList
  }
  const preImg = (file: File) => {
    let url = window.webkitURL || window.URL
    let imgfileurl = url.createObjectURL(file)
    setPicture(imgfileurl)
    return true
  }
  return (
    <div style={{ width: '700px' }}>
      <Bread bread={bread}></Bread>
      <Form
        name="basic"
        form={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        onFinish={onFinish}
        autoComplete="off"
        initialValues={videoInfo}
      >
        <Form.Item label="视频名称" name="title" rules={[{ required: origin === 'add', message: '请输入视频名称!' }]}>
          <Input />
        </Form.Item>
        <Form.Item
          label="上传视频"
          getValueFromEvent={normFile}
          name="videoFileList"
          rules={[{ required: origin === 'add', message: '请选择你要上传的视频!', type: 'array' }]}
        >
          <Upload {...videoProps} fileList={videoFileList}>
            <Button icon={<UploadOutlined />}>上传视频</Button>
          </Upload>
        </Form.Item>
        <Form.Item
          label="上传图片"
          name="fileList"
          getValueFromEvent={normFile}
          // rules={[{ required: origin === 'add', message: '请选择你要上传的图片!', type: 'array' }]}
        >
          <Upload {...props} fileList={fileList}>
            <Button icon={<UploadOutlined />}>上传图片</Button>
          </Upload>
        </Form.Item>
        <Form.Item label="预览图片">
          <Image src={picture} alt="预览图片" width={300} height={160} />
        </Form.Item>
        <Form.Item label="视频简介" name="introduce">
          <TextArea rows={4} />
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit" loading={loading}>
            {origin === 'add' ? '添加视频' : '更新视频'}
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}

export default AddVideo
